package ace.module.account.core.impl.service.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.core.model.PageResultDto;
import ace.cmp.core.model.R;
import ace.cmp.spring.data.jdbc.querydsl.core.converter.PageConverter;
import ace.module.common.api.model.input.PageInput;
import ace.module.account.api.model.dto.IamAccountPassportDto;
import ace.module.account.api.model.input.passport.IamAccountPassportSearchOutInput;
import ace.module.account.core.impl.converter.IamAccountPassportConverter;
import ace.module.account.core.impl.dao.entity.IamAccountPassport;
import ace.module.account.core.impl.dao.entity.IamApplication;
import ace.module.account.core.impl.dao.repository.IamAccountPassportRepository;
import ace.module.account.core.impl.manager.IamAccountPassportManager;
import ace.module.account.core.impl.manager.IamApplicationManager;
import ace.module.account.core.impl.service.IamAccountPassportService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/3/18 16:16
 */
@Component
@AllArgsConstructor
public class IamAccountPassportServiceImpl implements IamAccountPassportService {

  private final IamAccountPassportConverter accountPassportConverter;
  private final IamAccountPassportRepository accountPassportRepository;
  private final IamAccountPassportManager iamAccountPassportManager;
  private final IamApplicationManager iamApplicationManager;
  private final PageConverter pageConverter;

  @Override
  public IamAccountPassportDto getByIamAppIdAndPassport123AndPassportType(
      Long iamAppId,
      String passport,
      String passport2,
      String passport3,
      Integer passportType) {
    IamAccountPassport accountPassport =
        this.accountPassportRepository
            .getByIamAppIdAndPassportAndPassport2AndPassport3AndPassportTypeAndDeleteFlag(
                iamAppId,
                passport,
                passport2,
                passport3,
                passportType,
                CoreConstant.DELETE_FLAG_NOT);
    IamAccountPassportDto accountPassportDto =
        this.accountPassportConverter.convert(accountPassport);
    return accountPassportDto;
  }

  @Override
  public R<PageResultDto<IamAccountPassportDto>> search(
      PageInput<IamAccountPassportSearchOutInput> input) {
    IamApplication iamApplication = this.iamApplicationManager.getAndCheckByOutTypeAndOutId(
        input.getData().getOutInfo().getOutType(),
        input.getData().getOutInfo().getOutId()
    );

    Pageable pageable = pageConverter.toPageRequest(input.getPage());

    Page<IamAccountPassportDto> pageResult = this.iamAccountPassportManager.search(
        iamApplication.getId(),
        input.getData().getFilter(),
        pageable
    );

    PageResultDto<IamAccountPassportDto> resultDto = pageConverter.to(pageResult);

    return R.ok(resultDto);
  }
}
